package com.efounder.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.efounder.activity.AbActivity;
import com.efounder.ospmobilelib.R;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.view.titlebar.AbTitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
//假如用到位置提醒功能，需要import该类


public class WeatherFragment extends Fragment  {
	public static final String TAG = "FragmentFirst";
	AbTitleBar mTitleBar;
	AbBottomBar mBottomBar;
	Bitmap weatherBitmap;
	//private BDLocation bdLocation;    
	View rootView;
	//public LocationClient mLocationClient = null;
	//public BDLocationListener myListener = new MyLocationListener();

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 加载布局文件
		rootView = inflater.inflate(R.layout.fragment_fir, null);
		mTitleBar = ((AbActivity) getActivity()).getTitleBar();
		mTitleBar.setVisibility(View.GONE);

		//mLocationClient = new LocationClient(this.getActivity()); // 声明LocationClient类
		//mLocationClient.registerLocationListener(myListener);
		//initLocation() ;
		return rootView;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		mTitleBar.setTitleText("ESPMobile");
		super.onResume();
	}

	/*private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(0);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
		option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
		mLocationClient.start();  
	}*/

	/*public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			  if (null == location) {  
		            if (bdLocation != null) {  
		                bdLocation = null;  
		            } 
			  }
		    bdLocation = location;  
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());// 单位：公里每小时
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\nheight : ");
				sb.append(location.getAltitude());// 单位：米
				sb.append("\ndirection : ");
				sb.append(location.getDirection());// 单位度
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");
				requestWeather(); 

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				// 运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
				sb.append("\ndescribe : ");
				sb.append("网络定位成功");
				requestWeather(); 
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			List<Poi> list = location.getPoiList();// POI数据
			if (list != null) {
				sb.append("\npoilist size = : ");
				sb.append(list.size());
				for (Poi p : list) {
					sb.append("\npoi= : ");
					sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
				}
			}
			Log.i("BaiduLocationApiDem", sb.toString());
		}
	} */


    private void requestWeather() {  
        final Handler myHandler = new Handler() {  
            @Override  
            public void handleMessage(Message msg) {  
            	   JSONObject object = (JSONObject) msg.obj;  
                if (msg != null && null!=object){
                try {  
                	
                    int code = object.getInt("errNum");  
                    String states = object.getString("errMsg");  
                    if (code == 0 && states.equals("success")) {  
                       /* JSONArray results = object.getJSONArray("retData");  
                        JSONObject resultObj = results.getJSONObject(0);  
                        JSONArray weatherArray = resultObj.getJSONArray("weather_data");  
                        JSONObject weatherObj = weatherArray.getJSONObject(0);  
                          
                        String dayPictureUrl = weatherObj.getString("dayPictureUrl");  
                        String nightPictureUrl = weatherObj.getString("nightPictureUrl");*/  
                          
                        //TODO 增加日间、夜间的判断  
                       /* int tag = DateUtil.judgeAmOrPm();  
                        if (tag == 0) {         //上午  
                            getWeatherBitmap(dayPictureUrl);  
                        } else {                //下午  
                            getWeatherBitmap(nightPictureUrl);  
                        }  */
                    	JSONObject result = object.getJSONObject("retData");
                    } else {  
                        Log.d(TAG, "天气信息获取失败,code=" + code);  
                    }  
                } catch (JSONException e) {  
                    Log.d(TAG, "天气信息Json解析错误");  
                    e.printStackTrace();  
                }  
                }
                super.handleMessage(msg);  
            }  
        };  
  
        /*new Thread(new Runnable() {  
            public void run() {  
                JSONObject result = getWeatherJson();  
                Message msg = Message.obtain();  
                msg.obj = result;  
                myHandler.sendMessage(msg);  
            }  
  
            private JSONObject getWeatherJson() {  
                // TODO location获取成功调用requestWeather 所以不存在location为空的情况  
                String city = bdLocation.getCity();  
                
                if (city.contains("市")) {  
                    city = city.replace("市", "");
                }  
                //拼凑百度天气请求的完整url  
                StringBuffer url = new StringBuffer();  
                Activity activity = getActivity(); 
                if (isAdded() && activity != null) {
                	 url.append(getString(R.string.url_weather));
                }
               
                try {
                	Log.i("xxxxxxxxxxxxx", url.toString());
					city = URLEncoder.encode(city,"UTF-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                url.append(city);  
                //url.append("&output=json&ak=");  
                //url.append(getString(R.string.baidu_server_key));  
               
                URL urlCon;
                HttpURLConnection conn;
                JSONObject json =null;
                BufferedReader reader = null;
                StringBuffer sbf = new StringBuffer();
                String result = null;
                try {
                	urlCon = new URL(url.toString());
                    HttpURLConnection connection = (HttpURLConnection) urlCon
                            .openConnection();
                    connection.setRequestMethod("GET");
                    // 填入apikey到HTTP header
                    connection.setRequestProperty("apikey",  "781bb539a173cbac28cb04f6605ed414");
                    connection.connect();
                    InputStream is = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String strRead = null;
                    while ((strRead = reader.readLine()) != null) {
                        sbf.append(strRead);
                        sbf.append("\r\n");
                    }
                    reader.close();
                    result = sbf.toString();
                    Log.i("xxx", result);
                    json = new JSONObject(result); 
                } catch (Exception e) {
                    e.printStackTrace();
                }
				try {
					urlCon = new URL(url.toString());
					conn = (HttpURLConnection) urlCon.openConnection();
					conn.setRequestMethod("GET");
					if (conn.getResponseCode() == 200) {  
						InputStream in = conn.getInputStream();
					    byte[] data = readStream(in);   // 把输入流转换成字符数组     
					    Log.i("xxx", data.toString());
					    json = new JSONObject(data.toString());        // 把字符数组转换成字符串 
					  
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
			     catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
                
                catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

                return json;  
            }  
        }).start();  */
    }  
      
    /** 
     * 获取图片url对应的bitmap 
     * @return  
     */  
    private void getWeatherBitmap(final String url) {  
        final Handler myHandler = new Handler() {  
            @Override  
            public void handleMessage(Message msg) {  
                if (msg == null) {  
                    return;  
                }  
                weatherBitmap = (Bitmap) msg.obj;  
                Log.d(TAG, "weatherBitmap convert ok!");  
                  
                mergeBitmap();  
                super.handleMessage(msg);  
                //mLocationClient.stop();
            }  
        };  
  
        new Thread(new Runnable() {  
            public void run() {  
               // Bitmap bitmap = ImageUtil.getNetImage(url, 1);  
            	Bitmap bitmap = GetLocalOrNetBitmap(url);
                Message msg = Message.obtain();  
                msg.obj = bitmap;  
                myHandler.sendMessage(msg);  
            }  
        }).start();  
    }  
      
    private String fileName = "location_weather.jpg";  
      
    /** 
     * 合并天气、地理位置为bitmap 
     * @return
     */  
    private Bitmap mergeBitmap() {  
       /* if (bdLocation == null && weatherBitmap == null) {  
            return null;  
        }  */
        Bitmap mergeBitmap = null; 
      /* 
        if (bdLocation != null && weatherBitmap != null) {  
            mergeBitmap = ImageUtil.mergeBitmap(this, weatherBitmap, TextUtils.isEmpty(bdLocation.getAddrStr())?"":bdLocation.getAddrStr());  
        } else if (bdLocation != null){  
            mergeBitmap = ImageUtil.convertFontBitmap(this, TextUtils.isEmpty(bdLocation.getAddrStr())?"":bdLocation.getAddrStr());  
        }  
        // save 操作  
        //String filePath = FileUtil.saveBitmap(fileName, mergeBitmap);  
        String filePath = FileUtil.saveBitmap(fileName, mergeBitmap);  */
          
        //Intent intent = new Intent(getString(R.string.location_receiver));  
        //intent.putExtra("mergeBitmap", mergeBitmap);  
        //intent.putExtra("fileName", fileName);  
        //getApplication().sendBroadcast(intent);  
          
        /*SharedPreferences mSharedPreferences = getSharedPreferences("real_video_camera", 0);  
        SharedPreferences.Editor mEditor = mSharedPreferences.edit();   
        mEditor.putString(getString(R.string.key_location_file_path), filePath);  
        mEditor.commit();    
          
        Log.d(TAG, "mergeBitmap ok");  */
          
        return mergeBitmap;  
    }  
    
    /**   
     * 把输入流转换成字符数组   
     * @param inputStream   输入流   
     * @return  字符数组   
     * @throws Exception   
     */    
    public  byte[] readStream(InputStream inputStream) throws Exception {     
        ByteArrayOutputStream bout = new ByteArrayOutputStream();     
        byte[] buffer = new byte[1024];     
        int len = 0;     
        while ((len = inputStream.read(buffer)) != -1) {     
            bout.write(buffer, 0, len);     
        }     
        bout.close();     
        inputStream.close();     
    
        return bout.toByteArray();     
    }     
    
    public  Bitmap GetLocalOrNetBitmap(String url)  
    {  
        Bitmap bitmap = null;  
        InputStream in = null;  
        BufferedOutputStream out = null;  
        try  
        {  
            in = new BufferedInputStream(new URL(url).openStream(), 2*1024);  
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();  
            out = new BufferedOutputStream(dataStream, 2*1024);  
            copy(in, out);  
            out.flush();  
            byte[] data = dataStream.toByteArray();  
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
            data = null;
            in.close();
            return bitmap;  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
            return null;  
        }  
    }  
    private  void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[2*1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
}
